<template>
<div id="signIn" class="signIn">
    <div class="signIn_top">
        <calendar ref="calendar1"
            :events="calendar1.events" 
            :lunar="calendar1.lunar" 
            :value="calendar1.value" 
            :begin="calendar1.begin" 
            :end="calendar1.end" 
            @selectDate="setSelectDate"
            @selectMonth="changeSelectMonth"
            @selectYear="calendar1.selectYear"></calendar>
    </div>    
    <div class="signIn_btn" v-if="todaySigned == 0" @click="signIn">立即签到</div>
    <div class="signIn_btn" style="color: #ccc" v-else>今天已签到</div>
    <div class="signIn_rule">
        <p class="title">活动说明</p>
        <div class="rule_con" v-html="activityInfo.activityDesc">
        </div>
    </div>
    <div class="lj"></div>
    <div class="signIn_record">
        <p class="title">中奖信息</p>
        <div class="record_con">
            <div v-for="item in winnInfoList" :key="item.key">
                <div v-html="item.value"></div>
            </div>
        </div>
    </div>
    <div class="lj"></div>
    <div class="signIn_pm">
        <div class="pm_box">
            <div class="pm_box_con">
                <ul v-show="loginStatus == '0'">
                    <li style="color:#727272;width:50%">登录后才能查看到您的排名</li>
                    <li style="width:50%"></li>
                </ul>
                <ul v-show="loginStatus == '1'">
                    <li v-show="conSignedInfo != ''" class="td0">{{conSignedInfo}} </li>
                </ul>
                <ul v-show="loginStatus == '1'">
                    <li v-show="totalSignedInfo != ''" class="td0">{{totalSignedInfo}} </li>
                </ul>
                <ul style="border-top:2px solid #BCBCBC;">
                    <li style="font-size:0.25rem;font-weight:bold;width:20%;">排名</li>
                    <li style="font-size:0.25rem;font-weight:bold;width:20%;">用户手机号</li>
                    <li style="font-size:0.25rem;font-weight:bold;width:27%;">连续签到天数</li>
                    <li style="font-size:0.25rem;font-weight:bold;width:33%;">签到时间</li>
                </ul>
                <ul v-for="(item, index) in signContinuousList" :key="index">
                    <li v-if="item.memberId == userid" class="td1 active">{{item.rank}} </li>
                    <li v-else class="td1">{{item.rank}}</li>
                    <li v-if="item.memberId == userid" class="td2 active">{{item.memberMobile}}</li>
                    <li v-else class="td2">{{item.memberMobile}}</li>
                    <li v-if="item.memberId == userid" class="td3 active">{{item.daysContinuous}}</li>
                    <li v-else class="td3">{{item.daysContinuous}}</li>
                    <li v-if="item.memberId == userid" class="td4 active">{{item.signTimeStr}}</li>
                    <li v-else class="td4">{{item.signTimeStr}}</li>
                </ul>
                <ul style="border-top:2px solid #BCBCBC;">
                    <li style="font-size:0.25rem;font-weight:bold;width:20%;">排名</li>
                    <li style="font-size:0.25rem;font-weight:bold;width:20%;">用户手机号</li>
                    <li style="font-size:0.25rem;font-weight:bold;width:27%;">累计签到天数</li>
                    <li style="font-size:0.25rem;font-weight:bold;width:33%;">签到时间</li>
                </ul>
                <ul v-for="(item, index) in signTotalList" :key="index">
                    <li v-if="item.memberId == userid" class="td1 active">{{item.rank}} </li>
                    <li v-else class="td1">{{item.rank}}</li>
                    <li v-if="item.memberId == userid" class="td2 active">{{item.memberMobile}}</li>
                    <li v-else class="td2">{{item.memberMobile}}</li>
                    <li v-if="item.memberId == userid" class="td3 active">{{item.daysTotal}}</li>
                    <li v-else class="td3">{{item.daysTotal}}</li>
                    <li v-if="item.memberId == userid" class="td4 active">{{item.signTimeStr}}</li>
                    <li v-else class="td4">{{item.signTimeStr}}</li>
                </ul>
            </div>
        </div>
    </div>
</div>
</template>

<script> 
import moment from 'moment'
import calendar from '@/components/calendar.vue'

export default {
    name: 'signIn',
    components: {
        calendar
    },
    data(){
        return {
            userid: "",
            loginStatus: "1",
            conSignedInfo: "",
            totalSignedInfo: "",
            activityInfo: {},
            signContinuousList: [],
            signTotalList: [],
            winnInfoList: [],
            selectedDate: '',
            todaySigned: 0,
            dateFormat: '-',
            calendar1:{
                value:[], //默认日期
                lunar:false,  //显示农历
                // weeks:['日', '一', '二', '三', '四', '五', '六'],
                // months:['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                // events:{
                //     '2018-4-1':'已签',
                //     '2018-4-2':'已签',
                //     '2018-4-3':'已签',
                //     '2018-4-5':'已签',
                // },
                selectDate(value){
                    // calendar.vue页面的 this.$emit("select", XXXX) 方法设定的值
                    console.log(value.toString());
                },
                selectMonth(month,year){
                    console.log(year,month)
                },
                selectYear(year){
                    console.log(year)
                },
                timestamp:Date.now()
            },            
        }
    },    
    created: function() {
        // 通过链接进入平台，但没有关注过公众号时,重新设定模式 
        // 取得浏览器的信息（无论有没有设定过都需要重新设定）
        let userAgent = navigator.userAgent.toLowerCase();
        // 企业微信浏览器多了wxwork
        if (userAgent.indexOf("wxwork") > -1) {
            this.$store.commit('inMode', 'qiye');
        } else {
            this.$store.commit('inMode', 'weixin');
        }

        // android终端、ios终端的判断
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; 
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); 
        if (isiOS) {
            this.dateFormat = "/";
        }

        this.userid = this.$store.state.userid;
        
        this.$dialog.loading.open("请稍后");
        this.init();

        // 签到时需要跳转到登录时页面时，登录的跳转判断条件
        // 从员工关爱平台的广告栏进入该页面时this.$store.state.routerTo ="/"
        // 从微信公众的TAB菜单进入该页面时this.$store.state.routerTo = "/signIn"
        if (this.$store.state.routerTo != "/signIn") {
            this.$store.commit('routerTo', '/signIn');
        }
    },
    mounted: function() {
        // 该页面的上级section节点
        document.getElementById("scrollView").scrollTop = 0;
    },
    methods:{        
        init() {
            // 活动说明的取得
            this.$axios.get(this.CONSTANT.wapiBaseUrl + "activitySignIn/activityInfo")
                .then(response => {
                    if (response.status == 200) {
                        let activityList = response.data.object; 
                        // 只取的第一条
                        if (activityList.length > 0) {
                            this.activityInfo =  activityList[0];
                        }

                        // 用户ID有的场合，取得中奖信息
                        if (this.userid) {
                            this.getSignInList();
                        } else {
                            // 取得排行榜信息
                            this.getLeaderboardList();
                            this.loginStatus = "0"; // 未登录
                            this.userid = '';
                        }
                    } else {
                        this.$dialog.loading.close();
                        this.$dialog.toast({
                            mes: '活动说明的取得失败，请联系客服',
                            icon: 'error',
                            timeout: 1500
                        });
                    }
                })
                .catch(error => {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: '活动说明的取得失败，请联系客服',
                        icon: 'error',
                        timeout: 1500
                    });
                });
        },        
        getSignInList() {
            // 用户中奖信息的取得
            this.$axios.get(this.CONSTANT.wapiBaseUrl + "activitySignIn/signInList")
                .then(response => {
                    // 重新设置中奖信息LIST
                    this.winnInfoList = [];
                    if (response.status == 200) {
                        let activitySignList = response.data.object;
                        // 中奖信息、签到信息的设定
                        if (activitySignList.length > 0) {
                            // {'2018-2-10':'已签到', '2018-3-12':'已签到', ....}
                            let signStr = '{';
                            for (var i = 0; i < activitySignList.length; i++) {
                                let activitySign = activitySignList[i];
                                // 礼品状态 0:未到领取时间 1:未领取 2:已领取
                                // 中奖信息的设定
                                if (activitySign.giftState == "1") {
                                    // let recHtml = '<span>' + activitySign.giftDescription + '(' + activitySign.signDateStr +')' + '</span>';
                                    let recHtml = activitySign.signDateStr + "<br>" + '<span style="margin-left:0.5rem">' + activitySign.giftDescription  + '</span>';
                                    let winnInfo = {key:activitySign.signId, value:recHtml};
                                    this.winnInfoList.push(winnInfo);
                                }
                                
                                // 签到信息的设定
                                // 把月、日的前缀0去掉
                                let signDateStr = activitySign.signDateStr;
                                let arrSignDate = signDateStr.split("-");
                                signDateStr = arrSignDate[0] +  this.dateFormat + parseInt(arrSignDate[1]) +  this.dateFormat + parseInt(arrSignDate[2]);
                                signStr = signStr + '"' + signDateStr + '":"已签到", ';

                                // 判断今天是否已签到
                                let today = new Date().getTime();
                                today = moment(today).format("YYYY-MM-DD");
                                if (activitySign.signDateStr == today) {
                                    this.todaySigned = 1;
                                }
                            }
                            signStr = signStr.substr(0, signStr.length - 2);
                            signStr = signStr + '}';
                            // this.calendar1.events = {
                            //                         "2018-4-02":"已签到",
                            //                         "2018-4-24":"已签到",
                            //                     };
                            // window.alert(this.calendar1.events);
                            this.calendar1.events = JSON.parse(signStr);
                        }
                        // 中奖信息的设定
                        if (this.winnInfoList.length == 0) {
                            let recHtml = '<span>您还没有中奖</span>';
                            let winnInfo = {key:1, value:recHtml};
                            this.winnInfoList.push(winnInfo);
                        }

                        // 取得排行榜信息
                        this.getLeaderboardList();
                    } else {
                        // 401 权限不足时，标识没有登录
                        let recHtml = '<span>登录后才能查看中奖信息</span>';
                        let winnInfo = {key:1, value:recHtml};
                        this.loginStatus = "0"; // 未登录
                        this.userid = '';
                        this.winnInfoList.push(winnInfo);
                        // 取得排行榜信息
                        this.getLeaderboardList();
                    }
                })
                .catch(error => {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: '中奖信息取得失败，请联系客服',
                        icon: 'error',
                        timeout: 1500
                    });
                });
        },
        getLeaderboardList() {
            // 排行榜信息的取得
            this.$axios.get(this.CONSTANT.wapiBaseUrl + "activitySignIn/leaderboardList?activityId="+this.activityInfo.activityId+"&memberId="+this.userid)
                .then(response => {
                    this.$dialog.loading.close();
                    if (response.status == 200) {
                        // 手机号，隐藏中间四位(java处理)
                        // 排名字段：rowId(序号)  rank(不连续排名) densRank(连续排名)  rankValue(使用值)
                        // 暂无分页处理
                        this.signContinuousList = response.data.object.topContinuousList; 
                        this.signTotalList = response.data.object.topTotalList; 
                        // 取得当前用户的排名
                        if (this.loginStatus == "1") {
                            let oneContinuousSign = response.data.object.oneContinuousSign; 
                            let oneTotalSign = response.data.object.oneTotalSign; 

                            if (oneContinuousSign != null) {
                                // this.conSignedInfo = "您已连续签到" + oneContinuousSign.daysContinuous + "天，排名:第" + oneContinuousSign.rowId + "名";
                                this.conSignedInfo = "您已连续签到" + oneContinuousSign.daysContinuous + "天，排名:第" + oneContinuousSign.rank + "名";
                            } else {
                                this.conSignedInfo = "您的连续签到数据暂无";
                            }
                            if (oneTotalSign != null) {
                                // this.totalSignedInfo = "您已累计签到" + oneTotalSign.daysTotal + "天，排名:第" + oneTotalSign.rowId + "名";
                                this.totalSignedInfo = "您已累计签到" + oneTotalSign.daysTotal + "天，排名:第" + oneTotalSign.rank + "名";
                            } else {
                                this.totalSignedInfo = "您的累计签到数据暂无";
                            }
                        }
                    } else {
                        this.$dialog.toast({
                            mes: '排行榜信息取得失败，请联系客服',
                            icon: 'error',
                            timeout: 1500
                        });
                    }
                })
                .catch(error => {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: '排行榜信息取得失败，请联系客服',
                        icon: 'error',
                        timeout: 1500
                    });
                });
        },
        changeSelectMonth(yearMonth, day) {
            // yyyy-mm-dd 或 yyyy/mm/dd
            this.selectedDate = yearMonth +  this.dateFormat + day;
        }, 
        setSelectDate(selectedDate) {
            // calendar组件的的 this.$emit("selectDate", selectedDate) 方法
            // yyyy-mm-dd 或 yyyy/mm/dd
            this.selectedDate = selectedDate;
        },
        signIn() {            
            // 先登录。。            
            if (this.loginStatus == "0") {
                // this.$router.push("/fastLogin?page=signIn");
                this.$dialog.confirm({
                    title: '确认',
                    mes: '请登录后才能签到。确定要登录？',
                    opts: [
                        {
                            txt: '取消',
                            color: false,
                            callback: () => {
                                // 什么也不处理
                            }
                        },
                        {
                            txt: '确定',
                            color: true,
                            callback: () => {
                                this.$router.push("/fastLogin?page=signIn");
                            }
                        }
                    ]
                });

                return false;
            }

            // 选择的日期的判断
            let selectDateTime = new Date(this.selectedDate).getTime();
            let selectDate = moment(selectDateTime).format("YYYY-MM-DD");
            let now = new Date().getTime();
            now = moment(now).format("YYYY-MM-DD");
            if (selectDate != now) {
                this.$dialog.toast({
                    mes: '选择的签到日期必须是今天！',
                    timeout: 1000
                });

                // 记录当前选择的年月(比较用)
                let selectYear = selectDate.split("-")[0];
                let selectMonth = selectDate.split("-")[1];
                // 调用子组件的方法
                setTimeout(() => {
                    this.$refs.calendar1.setToday(selectYear, selectMonth, "D");
                }, 1005);
                return false;
            }
            // 登录签到信息(activityId需要)
            let signsRecord = {
                    activityId: this.activityInfo.activityId,
                    signTime: selectDateTime/1000, 
                    signTimeStr: moment(selectDateTime).format("YYYY-MM-DD HH:mm:ss")
                }

            this.$dialog.loading.open('请稍后');
            this.$httpAjax.post(this.CONSTANT.wapiBaseUrl + 'activitySignIn/addSign', signsRecord)
                .then((response) => {
                    this.$dialog.loading.close();
                    if (response.status == 200) {
                        if (response.data.status == 1) {
                            this.$dialog.toast({
                                mes: '签到成功',
                                icon: 'success',
                                timeout: 1200
                            });
                            // 重新取得页面数据
                            setTimeout(() => {
                                this.calendar1.value = [];
                                this.init();
                            }, 600);
                        } else {
                            // Exception时、response.data.status == -1
                            // this.$dialog.toast({
                            // 重复签到
                            if (response.data.errorCode == '0') {
                                this.$dialog.alert({mes:response.data.msg});
                            } else {
                                this.$dialog.alert({mes:'签到失败，请联系客服：' + response.data.msg});
                            }
                        }
                    }
                }).catch((error) => {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: '签到失败，请稍后重试' + error,
                        icon: 'error',
                        timeout: 1500
                    });
                });
        }
    }
}
</script>

<style scoped>
.signIn {
    width: 100%;
    height: 29rem;
    overflow: hidden;
    background:#CE404C;
}
/* 日历 */
.signIn_top {
    width: 100%;
    height: 7.3rem;
    box-sizing: border-box;
    line-height: 0.8rem;
    font-size: 0.3rem;
    color: #A1A1A1;
    padding: 0.2rem 0.24rem;
}
/* 签到按钮 */
.signIn_btn {
    width: 100%;
	text-align: center;
    margin-top: 0.2rem;
    height:1.2rem;
    text-align: center;
    line-height: 56px;
	font-size: 26px;
	color:#C65600;
	cursor: pointer;
    background: url(../../assets/btn.png) no-repeat center;
    background-size: contain;
}
/* 活动说明 */
.signIn_rule {
    width: 6.7rem;
    height: auto;
    margin:  0.3rem 0.4rem;
    min-height: 5rem;
    background:#f9ebe8;
    background-size: contain;
    border: 5px solid #42210b;
    box-sizing: border-box;
    border-radius: 0.5rem;
    padding: 0.2rem;
}
p.title {
	font-size: 16px;
	color:#333;
	font-weight: bold;
}
.rule_con {
    padding: 20px 10px;
    height: 4.5rem;
    color: #727272;
    overflow-x: hidden;
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
}
.lj {
    display: block;
    margin-top: -0.5rem;
    width: 100%;
    height: 0.88rem;
    position: absolute;
    /* bottom:0.1rem; */
    /* left:-0.1rem; */
    background: url(../../assets/lj.png) center no-repeat;
    background-size: contain;
    z-index: 999;
}
/* 中奖信息 */
.signIn_record {
    width: 6.7rem;
    height: auto;
    margin:  0.4rem 0.4rem;
    min-height: 3.5rem;
    background:#f9ebe8;
    background-size: contain;
    border: 5px solid #42210b;
    box-sizing: border-box;
    border-radius: 0.5rem;
    padding: 0.2rem;
}
.record_con {
    padding: 20px 10px;
    height: 3.5rem;
    color: #727272;
    overflow-x: hidden;
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
}
/* 签到排行榜 */
.signIn_pm {
    /* margin: 0 auto; */
    margin: -0.1rem auto;
    width: 6.7rem;
    height: 9rem;
    background:url(../../assets/yd_pm.png) center no-repeat;
    background-size: contain;
    padding: 0.1rem;
    box-sizing: border-box;
    overflow: hidden;
}
.pm_box{
    margin-top: 1.0rem;
    height: 7.8rem;
    overflow: hidden;
}
/* .pm_box_top{
    height: 0.5rem;
    margin-bottom: 0.05rem;
    overflow: hidden;
}
.pm_box_top ul{
    height: 0.5rem;
}
.pm_box_top ul li{
    height: 0.5rem;
    float: left;
    box-sizing: border-box;
    text-align: center;
    font-size: 0.25rem;
	font-weight: bold;
}
.pm_box_top ul li.td1 {
    width: 20%;
}
.pm_box_top ul li.td2 {
    width: 22%;
}
.pm_box_top ul li.td3 {
    width: 26%;
}
.pm_box_top ul li.td4{
    width: 32%;
} */
.pm_box_con{
    height: 7.7rem;
    overflow: auto;
}
.pm_box_con ul{
    height: 0.5rem;
    margin-bottom: 0.05rem;
}
.pm_box_con ul:last-child{
    height: 0.5rem;
    margin-bottom: 0.1rem;
}
.pm_box_con ul li{
    float: left;
    text-align: center;
    line-height: 0.5rem;
    font-size: 0.22rem;
}
.pm_box_con ul li.td0{
    width: 90%;
    margin-left: 0.2rem;
    font-size: 0.27rem;
    color:#C65600;
	font-weight: bold;
    text-align: left;
}
.pm_box_con ul li.td1{
    width: 15%;
}
.pm_box_con ul li.td2{
    width: 25%;
}
.pm_box_con ul li.td3{
    width: 20%;
}
.pm_box_con ul li.td4{
    width: 40%;
}

.active {
    background: #E94738;
    color: #fff;
}
</style>
